package com.cxria.springboottest.utils;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

@Component
class MyObjectMapper extends ObjectMapper {

	MyObjectMapper() {
		SimpleModule module = new SimpleModule();
		module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
		module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
		this.registerModule(module);
		this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
	}

	class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
		@Override
		void serialize(LocalDateTime value, JsonGenerator jgen, SerializerProvider provider)
				throws IOException, JsonProcessingException {
			jgen.writeNumber(Timestamp.valueOf(value).getTime());
		}
	}

	class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
		@Override
		LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
			long timestamp = jsonParser.getValueAsLong();
			Date date = new Date(timestamp);
			Instant instant = date.toInstant();
			ZoneId zoneId = ZoneId.systemDefault();
			LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
			return localDateTime;
		}
	}

}

